package ru.urfc.portal.services;

import java.io.IOException;
import java.io.Writer;

import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import ru.urfc.portal.model.documents.Document;

@Stateless
public class DmsTest {

//	@Resource(name = "webTrackerConnFactory", mappedName = "webTrackerConnFactory")
//	private QueueConnectionFactory qFactory;
//
//	@Resource(name = "webTrackerQueue", mappedName = "webTrackerQueue")
//	private Queue queue;

	public static void TestHtmlContent(long docId, Writer contentWriter) {
		try {
			contentWriter.write("123 " + docId);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static Document getTestDoc(EntityManager sys) {
		String sql = "select doc from Document doc";
		Document doc = (Document) sys.createQuery(sql).getResultList().get(0);
		return doc;
	}
	public static void testAdd(EntityManager sys) {
		Document doc = getTestDoc(sys);
		DmsMdb dmsMdb = new DmsMdb();
		dmsMdb.addDoc(sys, doc);
	}

	public static void testGet(EntityManager sys) {
		RefreshDocStates rds = new RefreshDocStates();
		rds.refreshStates(sys);
	}
	
	public void AddDoc(long docId) {
		// Get queue connection
		try {
			InitialContext jndi = new InitialContext();
			QueueConnectionFactory qFactory = (QueueConnectionFactory)jndi.lookup("dmsConnFactory");
			Queue queue = (Queue)jndi.lookup("dmsQueue");
			QueueConnection qConn;
			qConn = (QueueConnection) qFactory.createConnection();
			Session session = qConn.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			ObjectMessage msg = session.createObjectMessage();
			msg.setObject(docId);

			// Send JMS message
			session.createProducer(queue).send(msg);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
